package com.ruoyi.web.controller.system;

import java.util.*;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DoubleUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.ISysBuildingService;
import com.ruoyi.system.service.ISysLesseeService;
import com.ruoyi.system.service.ISysUnitService;
import com.ruoyi.system.utils.DayCompareUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 合同Controller
 * 
 * @author ruoyi
 * @date 2020-06-28
 */
@Controller
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController
{
    private String prefix = "system/tenant";

    @Autowired
    private ISysBuildingService sysBuildingService;

    @Autowired
    private ISysUnitService sysUnitService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysLesseeService sysLesseeService;

    @RequiresPermissions("system:tenant:view")
    @GetMapping()
    public String tenant()
    {
        return prefix + "/tenant";
    }

    /**
     * 查询合同列表
     */
    @RequiresPermissions("system:tenant:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysTenant sysTenant)
    {
        startPage();
        List<SysTenant> list = sysTenantService.selectSysTenantList(sysTenant);
        return getDataTable(list);
    }

    /**
     * 导出合同列表
     */
    @RequiresPermissions("system:tenant:export")
    @Log(title = "合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysTenant sysTenant)
    {
        List<SysTenant> list = sysTenantService.selectSysTenantList(sysTenant);
        ExcelUtil<SysTenant> util = new ExcelUtil<SysTenant>(SysTenant.class);
        return util.exportExcel(list, "在租合同");
    }

    /**
     * 导出在租合同列表
     */
    @RequiresPermissions("system:tenant:exportLiving")
    @Log(title = "导出在租合同", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLiving")
    @ResponseBody
    public AjaxResult exportLiving(SysTenant sysTenant)
    {
        sysTenant.setTenantStatus(TenantStatus.LIVEING.getCode());
        List<SysTenantExcel> list = sysTenantService.selectSysTenantExcelList(sysTenant);
        SysTenantExcel sysTenantExcelAll = sysTenantService.selectSysTenantExcelSum(sysTenant);

        //小数点保存两位
        for(SysTenantExcel listOne:list){
            sysTenantService.exchangeTwo(listOne);
        }



//        求合计
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setNumber(String.valueOf(i+1));
        }
        sysTenantExcelAll.setNumber("合计");
        sysTenantExcelAll.setUnitNameStr("");
        sysTenantExcelAll.setTenantName("");
        sysTenantExcelAll.setStartTime(null);
        sysTenantExcelAll.setEndTime(null);
        sysTenantExcelAll.setRisePriceFirstTime(null);
        sysTenantExcelAll.setRentStartDay(null);
        sysTenantExcelAll.setRemark("");
        list.add(sysTenantExcelAll);

        ExcelUtil<SysTenantExcel> util = new ExcelUtil<SysTenantExcel>(SysTenantExcel.class);
        return util.exportExcel(list, "在租合同");
    }
    /**
     * 导出离租合同 列表
     */
    @RequiresPermissions("system:tenant:exportLeave")
    @Log(title = "导出离租合同", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLeave")
    @ResponseBody
    public AjaxResult exportLeave(SysTenant sysTenant)
    {
        List<SysTenantExcel> list = sysTenantService.selectSysTenantLeaveExcelList(sysTenant);
        SysTenantExcel sysTenantExcelAll = sysTenantService.selectSysTenantExcelSum(sysTenant);
        //小数点保存两位
        for(SysTenantExcel listTwo:list){
            sysTenantService.exchangeTwo(listTwo);
        }
        //求合计
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setNumber(String.valueOf(i+1));
        }
        if(!list.isEmpty()){
            sysTenantExcelAll.setNumber("合计");
            sysTenantExcelAll.setUnitNameStr("");
            sysTenantExcelAll.setTenantName("");
            sysTenantExcelAll.setStartTime(null);
            sysTenantExcelAll.setEndTime(null);
            sysTenantExcelAll.setRisePriceFirstTime(null);
            sysTenantExcelAll.setRentStartDay(null);
            sysTenantExcelAll.setRemark("");
            list.add(sysTenantExcelAll);
        }
        ExcelUtil<SysTenantExcel> util = new ExcelUtil<SysTenantExcel>(SysTenantExcel.class);
        return util.exportExcel(list, "离租合同");
    }
    /**
     * 导出递增明细列表
     */
    @RequiresPermissions("system:tenant:exportRiseDetail")
    @Log(title = "导出合同递增明细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRiseDetail")
    @ResponseBody
    public AjaxResult exportRiseDetail(SysTenant sysTenant)
    {
        //获取合同和涨租表关联数据
        sysTenant.setTenantStatus(TenantStatus.LIVEING.getCode());
        List<SysTenantHigher> list = sysTenantService.selectSysTenantHigherExcelList(sysTenant);
        //遍历封装涨租明细集合
        List<SysTenantHigherExcel> excelList = new ArrayList<>();
        SysTenantHigherExcel sysTenantHigherExcel = new SysTenantHigherExcel();
        BeanUtils.copyProperties(list.get(0),sysTenantHigherExcel);
        sysTenantHigherExcel.setOne(list.get(0).getHigherRentFee());
        excelList.add(sysTenantHigherExcel);

        SysTenantHigher temp = list.get(0);
        for (int i = 1,j=0; i < list.size(); i++) {
            SysTenantHigher forTemp = list.get(i);
            if(forTemp.getTenantId().equals(temp.getTenantId())){
                if(!StringUtils.isNotBlank(excelList.get(j).getTwo())){
                    excelList.get(j).setTwo(forTemp.getHigherRentFee());
                } else if(!StringUtils.isNotBlank(excelList.get(j).getThree())){
                    excelList.get(j).setThree(forTemp.getHigherRentFee());
                } else if (!StringUtils.isNotBlank(excelList.get(j).getFour())){
                    excelList.get(j).setFour(forTemp.getHigherRentFee());
                } else {
                    excelList.get(j).setFive(forTemp.getHigherRentFee());
                }
            }else {
                SysTenantHigherExcel sysTenantHigherExcelTemp = new SysTenantHigherExcel();
                BeanUtils.copyProperties(forTemp,sysTenantHigherExcelTemp);
                sysTenantHigherExcelTemp.setOne(forTemp.getHigherRentFee());
                excelList.add(sysTenantHigherExcelTemp);
                temp = forTemp;
                j++;
            }
        }
        //押金保留小数点两位数
        for (SysTenantHigherExcel tenantHigherExcel : excelList) {
            sysTenantService.exchangeThree(tenantHigherExcel);
        }
        

        //求合计
        SysTenantHigherExcel allSysTenant = new SysTenantHigherExcel();
        if(!excelList.isEmpty()){
            double tenantArea = 0L,pledgeFee = 0L,one = 0L,two = 0L,three = 0L,four = 0L,five = 0L;
            for (int i = 0; i < excelList.size(); i++) {
                tenantArea+=Double.parseDouble(excelList.get(i).getTenantArea());
                if(StringUtils.isNotBlank(excelList.get(i).getPledgeFee())){
                    pledgeFee+=Double.parseDouble(excelList.get(i).getPledgeFee());
                }
                if(StringUtils.isNotBlank(excelList.get(i).getOne())){
                    one+=Double.parseDouble(excelList.get(i).getOne());
                }
                if(StringUtils.isNotBlank(excelList.get(i).getTwo())){
                    two+=Double.parseDouble(excelList.get(i).getTwo());
                }if(StringUtils.isNotBlank(excelList.get(i).getThree())){
                    three+=Double.parseDouble(excelList.get(i).getThree());
                }if(StringUtils.isNotBlank(excelList.get(i).getFour())){
                    four+=Double.parseDouble(excelList.get(i).getFour());
                }if(StringUtils.isNotBlank(excelList.get(i).getFive())){
                    five+=Double.parseDouble(excelList.get(i).getFive());
                }
                excelList.get(i).setNumber(String.valueOf(i+1));
            }
            allSysTenant.setTenantArea(String.valueOf(tenantArea));
            allSysTenant.setPledgeFee(String.valueOf(pledgeFee));
            allSysTenant.setOne(String.valueOf(one));
            allSysTenant.setTwo(String.valueOf(two));
            allSysTenant.setThree(String.valueOf(three));
            allSysTenant.setFour(String.valueOf(four));
            allSysTenant.setFive(String.valueOf(five));
            allSysTenant.setNumber("合计");
            excelList.add(allSysTenant);
        }

        ExcelUtil<SysTenantHigherExcel> util = new ExcelUtil<SysTenantHigherExcel>(SysTenantHigherExcel.class);
        return util.exportExcel(excelList, "递增明细");
    }

    /**
     * 新增合同
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        //返回楼栋
        mmap.put("building", sysBuildingService.selectSysBuildingAll());
        //返回合同
        SysLessee sysLessee = new SysLessee();
        mmap.put("lessee", sysLesseeService.selectSysLesseeList(sysLessee));
        return prefix + "/add";
    }

    /**
     * 新增合同 单元面积填充
     */
    @PostMapping("/addUnitArea")
    @ResponseBody
    public AjaxResult addUnitArea(String unitIdStr)
    {
        List<SysUnit> unitList = sysUnitService.selectSysUnitByIds(unitIdStr);
        double unitArea = 0L;
        for (SysUnit sysUnit : unitList) {
            unitArea+=sysUnit.getUnitArea();
        }
        return AjaxResult.success(unitArea);
    }

    /**
     * 新增合同单元下拉框
     */
    @PostMapping("/addUnitList")
    @ResponseBody
    public AjaxResult addUnitArea(Long buildingId)
    {
        Map map = new HashMap();
        List<SysUnit> unitList = sysUnitService.selectSysUnitByBuildingId(buildingId);
        if(unitList!=null && !unitList.isEmpty()){
//            unitList.removeIf(e->e.getUnitStatus().equals(UnitStatus.RENTING.getCode()));
            return AjaxResult.success(unitList);
        }
        return AjaxResult.error();
    }

    /**
     * 新增保存合同
     */
    @RequiresPermissions("system:tenant:add")
    @Log(title = "合同", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysTenant sysTenant)
    {
        List<SysTenant> oldTenants = sysTenantService.selectSysTenantByUnitId(sysTenant.getUnitIdStr()); //根据单元id获取数据
        SysTenant oldTenant = null;
        if (!CollectionUtils.isEmpty(oldTenants)) {             //判断非空
            oldTenant = oldTenants.get(oldTenants.size() - 1);
        }
        if (oldTenant != null) {
            Date dateTime1 = oldTenant.getEndTime();        //获取在租合同的结束时间
            Date dateTime2 = sysTenant.getStartTime();      //获取未租合同的开始时间
            int i = dateTime2.compareTo(dateTime1);
                if(i>0){
                    Double risePriceRatio = 0D;
                    if(StringUtils.isNotBlank(sysTenant.getRisePriceRatio())){
                        risePriceRatio = Double.parseDouble(sysTenant.getRisePriceRatio())*0.01;
                    }
                    sysTenant.setRisePriceRatio(risePriceRatio.toString());
                    sysTenant.setCreateBy(ShiroUtils.getLoginName());
                    sysTenant.setHigherRentFee(sysTenant.getMonthlyRentFee());
                    sysTenant.setNextHigherTime(sysTenant.getRisePriceFirstTime());
                    ShiroUtils.clearCachedAuthorizationInfo();
            }else {
                return AjaxResult.error("用户已出租");
            }
        }
        return toAjax(sysTenantService.insertSysTenant(sysTenant));
    }

    /**
     * 修改合同
     */
    @GetMapping("/edit/{tenantId}")
    public String edit(@PathVariable("tenantId") Long tenantId, ModelMap mmap)
    {
        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
        if (StringUtils.isNotBlank(sysTenant.getRisePriceRatio())){
            Double risePriceRatio =Double.parseDouble(sysTenant.getRisePriceRatio())*100;
            sysTenant.setRisePriceRatio(risePriceRatio.toString());
        }
        mmap.put("building", sysBuildingService.selectSysBuildingByTenantId(tenantId));
        sysTenant = sysTenantService.exchange(sysTenant);
        mmap.put("sysTenant", sysTenant);
        return prefix + "/edit";
    }

    /**
     * 编辑合同单元下拉列表
     */
    @PostMapping("/eidtUnitList")
    @ResponseBody
    public AjaxResult eidtUnitList(Long tenantId,Long buildingId)
    {
        Map map = new HashMap();
        List<SysUnit> unitList = sysUnitService.selectSysUnitByTenantId(tenantId,buildingId);
        if(unitList!=null && !unitList.isEmpty()){
            return AjaxResult.success(unitList);
        }
        return AjaxResult.error();
    }

    /**
     * 修改保存合同
     */
    @RequiresPermissions("system:tenant:edit")
    @Log(title = "合同", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysTenant sysTenant)
    {
        List<SysTenant> oldTenants = sysTenantService.selectSysTenantByUnitId(sysTenant.getUnitIdStr());
        SysTenant oldTenant = null;
//        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (!CollectionUtils.isEmpty(oldTenants)) {             //判断非空
            oldTenant = oldTenants.get(oldTenants.size() - 1);
        }
        if (oldTenant != null) {
            Date dateTime1 = oldTenant.getEndTime();                //取出上一租户合同的结束时间
            Date dateTime2 = sysTenant.getStartTime();              //取出下一租户的合同的开始时间
            int i = dateTime2.compareTo(dateTime1);                 //判断开始时间是否大于结束时间
            if(i>0){
                Double risePriceRatio = 0D;
                if(StringUtils.isNotBlank(sysTenant.getRisePriceRatio())){
                    risePriceRatio = Double.parseDouble(sysTenant.getRisePriceRatio())*0.01;
                }
                sysTenant.setRisePriceRatio(risePriceRatio.toString());
                sysTenant.setCreateBy(ShiroUtils.getLoginName());
                sysTenant.setHigherRentFee(sysTenant.getMonthlyRentFee());
                sysTenant.setNextHigherTime(sysTenant.getRisePriceFirstTime());
                ShiroUtils.clearCachedAuthorizationInfo();
            }
        }
        return toAjax(sysTenantService.updateSysTenant(sysTenant));
    }

    /**
     * 删除合同
     */
    @RequiresPermissions("system:tenant:remove")
    @Log(title = "合同", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        int rows = sysTenantService.deleteSysTenantByIds(ids);
        if(rows == 0){
            return new AjaxResult().error("该合同未离租");
        }
        return toAjax(rows);
    }

    /**
     * 合同离租
     */
    @GetMapping("/leave/{tenantId}")
    @Log(title = "合同离租", businessType = BusinessType.UPDATE)
    public String leaveView(@PathVariable("tenantId") Long tenantId, ModelMap mmap)
    {
        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
        mmap.put("sysTenant", sysTenant);
        return prefix + "/leave";
    }

    /**
     * 离租保存合同
     */
//    @RequiresPermissions("system:tenant:leaveSave")
    @Log(title = "合同", businessType = BusinessType.UPDATE)
    @PostMapping("/leaveSave")
    @ResponseBody
    public AjaxResult leaveSave(SysTenant sysTenant)
    {
        sysTenant.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysTenantService.leaveSysTenant(sysTenant));
    }

    /**
     * 合同续租
     */
    @GetMapping("/continue/{tenantId}")
    public String continueView(@PathVariable("tenantId") Long tenantId, ModelMap mmap)
    {
        SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
        mmap.put("sysTenant", sysTenant);
        return prefix + "/continue";
    }

    /**
     * 合同续租保存
     */
//    @RequiresPermissions("system:tenant:continue")
    @Log(title = "合同续租", businessType = BusinessType.INSERT)
    @PostMapping("/continue")
    @ResponseBody
    public AjaxResult continueSave(SysTenant sysTenant)
    {
        sysTenant.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysTenantService.insertSysTenantContinue(sysTenant));
    }

    /**
     * 涨租次数
     */
    @GetMapping("/risePriceNumberChange")
    @ResponseBody
    public AjaxResult risePriceNumberChange(String startTime, String endTime, String risePriceFirstTime)
    {
        //求两个时间相差几年
        int number = 1;
        SysDayCompare sysDayCompare = DayCompareUtils.dayCompareYear(DateUtil.parseYYYYMMDDDate(startTime),DateUtil.parseYYYYMMDDDate(endTime));
        //判断
        String[] startTimes = startTime.split("-");
        String[] endTimes = endTime.split("-");
        String[] risePriceFirstTimes = risePriceFirstTime.split("-");

        if(sysDayCompare.getYear()>1){
            number = sysDayCompare.getYear()-1;
//            int number = 0;
            //如果起始月日大于涨租时间  次数-1
            if(Integer.parseInt(startTimes[1])>Integer.parseInt(risePriceFirstTimes[1])
                    || (Integer.parseInt(startTimes[1]) == Integer.parseInt(risePriceFirstTimes[1])
                    && Integer.parseInt(startTimes[2])>Integer.parseInt(risePriceFirstTimes[2]))){
                number -= 1;
//                number +=1;
            }
            //如果终止月日大于涨租时间  次数+1
            if(Integer.parseInt(endTimes[1])>Integer.parseInt(risePriceFirstTimes[1])
                    || (Integer.parseInt(endTimes[1]) == Integer.parseInt(risePriceFirstTimes[1])
                    && Integer.parseInt(endTimes[2])>Integer.parseInt(risePriceFirstTimes[2]))) {
                number += 1;
            }
        }else {
            number = sysDayCompare.getYear();
//            int number = 0;
            //如果起始月日大于涨租时间  次数-1
            if(Integer.parseInt(startTimes[1])>Integer.parseInt(risePriceFirstTimes[1])
                    || (Integer.parseInt(startTimes[1]) == Integer.parseInt(risePriceFirstTimes[1])
                    && Integer.parseInt(startTimes[2])>=Integer.parseInt(risePriceFirstTimes[2]))){
                number -= 1;
//                number +=1;
            }
            //如果终止月日大于涨租时间  次数+1
            if(Integer.parseInt(endTimes[1])>Integer.parseInt(risePriceFirstTimes[1])
                    || (Integer.parseInt(endTimes[1]) == Integer.parseInt(risePriceFirstTimes[1])
                    && Integer.parseInt(endTimes[2])>Integer.parseInt(risePriceFirstTimes[2]))) {
                number += 1;
            }
        }
        return AjaxResult.success(number);
    }

    /**
     //     * 合同详情
     //     */
    @RequiresPermissions("system:tenant:detail")
    @GetMapping("/detail/{tenantId}")
    public String detail(@PathVariable("tenantId") Long tenantId, ModelMap mmap) {
       SysTenant sysTenant = sysTenantService.selectSysTenantById(tenantId);
       sysTenant = sysTenantService.exchange(sysTenant);
       Double risePriceRatio = Double.parseDouble(sysTenant.getRisePriceRatio())*100;
       sysTenant.setRisePriceRatio(String.valueOf(risePriceRatio));
        mmap.put("sysTenant",sysTenant);
        return prefix + "/detail";

    }
}
